package com.mfnote.view.paint;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.mfnote.view.R;
import com.mfnote.view.R.anim;
import com.mfnote.view.R.color;
import com.mfnote.view.R.drawable;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;
import com.mfnote.view.R.style;
import com.mfnote.db.dao.PaintDao;
import com.mfnote.model.PaintEntity;
import com.mfnote.util.ShareUtil;
import com.mfnote.util.image.ImageManager;

public class PaintView extends View implements OnClickListener {

	// 初始化颜色值
	int Red = getResources().getColor(R.color.Red);
	int Blue = getResources().getColor(R.color.Blue);
	int Purple = getResources().getColor(R.color.Purple);
	int Orange = getResources().getColor(R.color.Orange);
	int Black = getResources().getColor(R.color.Black);
	int Green = getResources().getColor(R.color.Green);
	int White = getResources().getColor(android.R.color.white);
	int ScreenWidth; //画布宽度
	int ScreenHeight; //画布高度
	int lineWidth; // 画笔宽度
	int linecolor; // 初始画笔颜色
	int linecolor2; // 选色后画笔颜色
	// 颜色块背景资源设置了6种
	ImageButton[] setcolors = new ImageButton[6];
	int colorIbtnIds[] = new int[] { R.id.newpaint_ib_Red,
			R.id.newpaint_ib_Blue, R.id.newpaint_ib_Orange,
			R.id.newpaint_ib_Black, R.id.newpaint_ib_Green,
			R.id.newpaint_ib_Purple };
	// 线条资源设置了粗细不同的六种
	ImageButton[] setlineWidth = new ImageButton[6];
	int lineIbtnIds[] = new int[] { R.id.newpaint_ib_line_1,
			R.id.newpaint_ib_line_2, R.id.newpaint_ib_line_3,
			R.id.newpaint_ib_line_4, R.id.newpaint_ib_line_5,
			R.id.newpaint_ib_line_6 };
	private float mX, mY; // 设置画笔坐标
	private static final float TOUCH_TOLERANCE = 4;//触摸阈值
	
	// 保存Path路径的集合,用List集合来模拟栈
	private static List<DrawPath> savePath;
	// 记录Path路径的对象
	private DrawPath dp;
	private class DrawPath {
		  public Path path;// 路径
		  public Paint paint;// 画笔
	}
	public Bitmap mBitmap; // 位图
	public Bitmap bm_paint_eraser, bm_paint_now, bm_paint_pen, newpaint_canvas,
			bmpOld;
	private Canvas mCanvas; // 画布
	private Path mPath; // 画笔路径
	private Paint mBitmapPaint; // 画笔
	private Paint mPaint; // 画笔
	View colorView, parentView,lineView,moreView;
	Matrix matrix = null; // 处理图片缩放旋转等动作
	LinearLayout ll_colorboard = null;
	GridView gv_Bottom_Menu = null; // 加载NewPaintActivity底部菜单
	PopupWindow pw_colorboard = null; // 颜色选择板
	PopupWindow pw_lineboard = null; // 线条粗细选择板
	PopupWindow pw_moreitem=null; // 点击更多弹出其他功能窗口

	EditText et_paint_title = null; // 获取用户输入的涂鸦文件名称
	String newpaint_title = null; // 保存涂鸦文件的名称
	String oldTitle = null; // 打开文件的名称
	String timeNow = null; // 系统当前时间
	PaintView instance;
	String pathName; // 打开已有文件获取其路径
	String filepath; // 点击保存时将当前画布保存在该路径下
	HashMap<String, Object> mapOld = null; // 打开某一条文件时获取数据库中对应的一行数据
	boolean saveSuccess=false;
	boolean showColorPopup = false;
	boolean showLinePopup = false;
	boolean showMorePopup = false;
	boolean isDrawing=false;
	LinearLayout newpaint_ll_share,newpaint_ll_clear,newpaint_ll_eraser;
	
	/** 声明构造方法 */
	@SuppressWarnings("unchecked")
	public PaintView(Context c, int ScreenWidth, int ScreenHeight) {
		super(c);

		instance = this;
		loadBottomMenu();
		saveSuccess=true;

		this.ScreenWidth = ScreenWidth;
		this.ScreenHeight = ScreenHeight;
		LayoutInflater flater = LayoutInflater.from(c);
		colorView = flater.inflate(R.layout.newpaint_colorboard, null);
		lineView = flater.inflate(R.layout.newpaint_lineboard, null);
		parentView = flater.inflate(R.layout.newpaint, null);
		moreView=flater.inflate(R.layout.newpaint_more_popup, null);

		linecolor = Black; // 设置画笔初始颜色
		linecolor2 = Black;
		lineWidth = 12; // 设置画笔初始宽度
		newpaint_canvas = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.newpaint_canvas);
		newpaint_canvas = ImageManager.zoomBitmap(newpaint_canvas, ScreenWidth,
				ScreenHeight); // 调整图片大小以适应屏幕
		bm_paint_pen = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.newpaint_pen); // 获取画笔
		bm_paint_eraser = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.eraser); // 获取橡皮
		bm_paint_now = bm_paint_pen; // 设置画图操作初始为画笔（点了橡皮后设置为橡皮）
		mBitmap = Bitmap.createBitmap(ScreenWidth, ScreenHeight,
				Bitmap.Config.ARGB_8888); // 图片质量选择ARGB_8888,32位
		mCanvas = new Canvas(mBitmap); // 创建一个空的画布
		mCanvas.drawColor(White); // 画布的背景色

		mBitmapPaint = new Paint(Paint.DITHER_FLAG); // 设置画笔风格
		lineset();
		savePath = new ArrayList<DrawPath>();
		find_ImageButtonId();

		et_paint_title = (EditText) NewPaintActivity.instance
				.findViewById(R.id.newpaint_et_title_name);

		// 点击listView列表后重新加载此界面
		Intent intent = NewPaintActivity.instance.getIntent();
		mapOld = (HashMap<String, Object>) intent
				.getSerializableExtra("paintmap");
		if (mapOld != null) { // 旧文件列表对应的一行数据
			oldTitle = mapOld.get("title").toString(); // 记下打开文件的名称
			loadPaintDetail();
		}
	}

	/** 加载底部菜单布局 */
	private void loadBottomMenu() {
		gv_Bottom_Menu = (GridView) NewPaintActivity.instance
				.findViewById(R.id.newpaint_gv_bottom_menu);
		gv_Bottom_Menu.setSelector(new ColorDrawable(Color.TRANSPARENT)); // 去掉自身自带的按下背景效果

		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = null;

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.newpaint_icon_pen);
		map.put("itemText", "画笔");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.undo);
		map.put("itemText", "撤销");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.newpaint_icon_color);
		map.put("itemText", "颜色");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.newpaint_icon_width);
		map.put("itemText", "线条");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.save);
		map.put("itemText", "保存");
		data.add(map);

		map = new HashMap<String, Object>();
		map.put("itemImage", R.drawable.more);
		map.put("itemText", "更多");
		data.add(map);

		SimpleAdapter adapter = new SimpleAdapter(NewPaintActivity.instance,
				data, R.layout.newpaint_item_menu, new String[] { "itemImage",
						"itemText" }, new int[] { R.id.item_image,
						R.id.item_text });
		gv_Bottom_Menu.setAdapter(adapter);

		gv_Bottom_Menu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0: { // 画笔
					linecolor = Black;
					lineset();
					break;
				}
				case 1: { // 撤销
					undo();
					break;
				}
				case 2: { // 颜色
					if (showColorPopup == false) {
						if (showLinePopup == true&&showMorePopup==false) {
							pw_lineboard.dismiss();
							showLinePopup = false;
						}else if(showLinePopup == false&&showMorePopup==true){
							pw_moreitem.dismiss();
							showMorePopup=false;
						}
						showColorPop(parent, colorView);
						showColorPopup = true;
					} else {
						pw_colorboard.dismiss();
						showColorPopup = false;
					}
					break;
				}
				case 3: { // 线条（粗细）
					// 第一次点击弹出PopupWindow,再次点击关闭窗口
					if (showLinePopup == false) {
						if (showColorPopup == true&&showMorePopup==false) {
							pw_colorboard.dismiss();
							showColorPopup = false;
						}else if(showColorPopup == false&&showMorePopup==true){
							pw_moreitem.dismiss();
							showMorePopup=false;
						}
						showLinePop(parent, lineView);
						showLinePopup = true;
					} else {
						pw_lineboard.dismiss();
						showLinePopup = false;
					}
					break;
				}
				case 4: { // 保存
					if(isDrawing==true){
						save();
					}else{
						Toast.makeText(NewPaintActivity.instance, "您还没画呢大师", Toast.LENGTH_SHORT).show();
					}
					break;
				}
				case 5: { // 更多
					// 第一次点击弹出PopupWindow,再次点击关闭窗口
					if (showMorePopup == false) {
						if (showColorPopup == true&&showLinePopup==false) {
							pw_colorboard.dismiss();
							showColorPopup = false;
						}else if(showColorPopup == false&&showLinePopup==true){
							pw_lineboard.dismiss();
							showLinePopup=false;
						}
						showMorePopup(parent);
						showMorePopup = true;
					} else {
						pw_moreitem.dismiss();
						showMorePopup = false;
					}
					break;
				}
				}
			}
		});
	}

	/** 点击更多后弹出其他菜单项 */
	private void showMorePopup(View parent) {
		newpaint_ll_eraser=(LinearLayout) moreView.findViewById(R.id.newpaint_ll_eraser);
		newpaint_ll_clear=(LinearLayout) moreView.findViewById(R.id.newpaint_ll_clear);
		newpaint_ll_share=(LinearLayout) moreView.findViewById(R.id.newpaint_ll_share);
		
		newpaint_ll_eraser.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				pw_moreitem.dismiss();
				linecolor = White;
				lineset();
			}
		});
		
		newpaint_ll_clear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				pw_moreitem.dismiss();
				clear();
				if(isDrawing==true){
					isDrawing=false;
				}
			}
		});
		
		newpaint_ll_share.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				pw_moreitem.dismiss();
				if(isDrawing==true){
					saveToSD();
					ShareUtil.share(filepath, "",
							NewPaintActivity.instance);
				}else{
					Toast.makeText(NewPaintActivity.instance, "您还没画呢大师", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		if(pw_moreitem == null) {
			pw_moreitem = new PopupWindow(moreView,LayoutParams.WRAP_CONTENT , LayoutParams.WRAP_CONTENT);
			//设置整个popupwindow的样式 
			pw_moreitem.setBackgroundDrawable(getResources().getDrawable(R.drawable.more_popup_bg_3_item));  
			//pw_moreitem.setAnimationStyle(R.style.AnimationPreview);
			
//			pw_moreitem.setFocusable(true);    //使窗口里面的控件显示其相应的效果，比较点击button时背景颜色改变。
//			pw_moreitem.update(); //将给popupWindow设置的属性更新加载一下
		}
		if(!pw_moreitem.isShowing()){
			//显示出来
			pw_moreitem.showAtLocation(parent, Gravity.BOTTOM|Gravity.RIGHT,0, gv_Bottom_Menu.getHeight());
		}
	}
	
	/** 获取颜色块和线条粗细图片资源并添加监听 */
	private void find_ImageButtonId() {

		// 加载调整画笔颜色的图片同时添加点击事件
		for (int i = 0; i < 6; i++) {
			setcolors[i] = (ImageButton) colorView
					.findViewById(colorIbtnIds[i]);
			setcolors[i].setOnClickListener(this);
		}

		// 加载调整画笔宽度的图片同时添加点击事件
		for (int i = 0; i < 6; i++) {
			setlineWidth[i] = (ImageButton) lineView
					.findViewById(lineIbtnIds[i]);
			setlineWidth[i].setOnClickListener(this);
		}

	}

	/** 颜色块和线条粗细的点击事件 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.newpaint_ib_Black:
			linecolor = Black;
			linecolor2 = Black;
			break;
		case R.id.newpaint_ib_Blue:
			linecolor = Blue;
			linecolor2 = Blue;
			break;
		case R.id.newpaint_ib_Green:
			linecolor = Green;
			linecolor2 = Green;
			break;
		case R.id.newpaint_ib_Orange:
			linecolor = Orange;
			linecolor2 = Orange;
			break;
		case R.id.newpaint_ib_Purple:
			linecolor = Purple;
			linecolor2 = Purple;
			break;
		case R.id.newpaint_ib_Red:
			linecolor = Red;
			linecolor2 = Red;
			break;
		case R.id.newpaint_ib_line_1:
			lineWidth = 6;
			linecolor = linecolor2;
			break;
		case R.id.newpaint_ib_line_2:
			lineWidth = 12;
			linecolor = linecolor2;
			break;
		case R.id.newpaint_ib_line_3:
			lineWidth = 18;
			linecolor = linecolor2;
			break;
		case R.id.newpaint_ib_line_4:
			lineWidth = 24;
			linecolor = linecolor2;
			break;
		case R.id.newpaint_ib_line_5:
			lineWidth = 30;
			linecolor = linecolor2;
			break;
		case R.id.newpaint_ib_line_6:
			lineWidth = 36;
			linecolor = linecolor2;
			break;
		}
		lineset();
		if (pw_colorboard != null) {
			pw_colorboard.dismiss(); // 选择颜色后关闭颜色选择板窗口
			showColorPopup = false;
		}
		if (pw_lineboard != null) {
			pw_lineboard.dismiss(); // 选择线条粗细后关闭线条选择板窗口
			showLinePopup = false;
		}
		// MainActivity.instance.isPopupWindow = false;
		postInvalidate(); // 重绘
	}

	/** 点击底部颜色选项弹出颜色选择板 */
	private void showColorPop(AdapterView<?> parent, View colorView) {
		if (pw_colorboard == null) {
			pw_colorboard = new PopupWindow(colorView,
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			pw_colorboard.setAnimationStyle(R.style.AnimationPreview_center); // 设置弹窗动画
			// pw_lineboard.setFocusable(true);
			// //使窗口里面的控件显示其相应的效果，比较点击button时背景颜色改变。
			// pw_lineboard.update(); //将给popupWindow设置的属性更新加载一下
		}
		if (!pw_colorboard.isShowing()) {
			pw_colorboard.showAtLocation(parentView, Gravity.BOTTOM
					| Gravity.CENTER, 55, gv_Bottom_Menu.getHeight()+5); // PopupWindow窗口在父窗口的显示位置
		}
	}

	/** 点击底部线条选项弹出线条选择板 */
	private void showLinePop(AdapterView<?> parent, View colorView) {
		if (pw_lineboard == null) {
			pw_lineboard = new PopupWindow(lineView,
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			pw_lineboard.setAnimationStyle(R.style.AnimationPreview_center); // 设置弹窗动画
			// pw_lineboard.setFocusable(true);
			// //使窗口里面的控件显示其相应的效果，比较点击button时背景颜色改变。
			// pw_lineboard.update(); //将给popupWindow设置的属性更新加载一下
		}
		if (!pw_lineboard.isShowing()) {
			pw_lineboard.showAtLocation(parentView, Gravity.BOTTOM
					| Gravity.CENTER, 55, gv_Bottom_Menu.getHeight()+5); // PopupWindow窗口在父窗口的显示位置
		}
	}

	/** 画笔设置 */
	public void lineset() {
		mPaint = new Paint(); // 创建画笔
		mPaint.setColor(linecolor); // 设置画笔初始颜色
		mPaint.setStyle(Paint.Style.STROKE); // 设置画笔类型为空心
		mPaint.setStrokeJoin(Paint.Join.ROUND); // 设置画笔结合处类型为圆弧，抹去矩角
		mPaint.setStrokeCap(Paint.Cap.ROUND); // 设置笔刷类型为圆滑状
		mPaint.setAntiAlias(true); // 打开抗锯齿
		mPaint.setDither(true); // 打开抗抖动
		if (linecolor == White) {
			mPaint.setStrokeWidth(20.0f); // 设置橡皮初始半径
			bm_paint_now = bm_paint_eraser;
		} else {
			bm_paint_now = bm_paint_pen;
			mPaint.setStrokeWidth(lineWidth); // 设置画笔半径
		}

	}

	/** 画图draw方法 */
	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
		if(mPath!=null){
			canvas.drawPath(mPath, mPaint);
		}
		canvas.drawBitmap(newpaint_canvas, 0, 0, mPaint);
		if (mX != 0 && mY != 0) {
			canvas.drawBitmap(bm_paint_now, mX, mY, mPaint);
		}

	}

	/** 画图过程触摸事件 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		// 获取当前触摸点坐标
		float x = event.getX();
		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			isDrawing=true;
			// 每次down下去重新new一个Path
			mPath = new Path();
			
			//每一次记录的路径对象是不一样的
			dp = new DrawPath();
			dp.path = mPath;
			dp.paint = mPaint;
			touch_start(x, y); // 设置画笔点击屏幕时的响应动作
			invalidate();
			break;
		case MotionEvent.ACTION_MOVE:
			touch_move(x, y); // 设置画笔在屏幕上移动时的响应动作
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			touch_up(x, y); // 设置画笔离开屏幕时的响应动作
			invalidate();
			break;
		}
		return true;
	}

	/** 画笔初始位置设置 */
	private void touch_start(float x, float y) {
		mPath.moveTo(x, y);
		mX = x;
		mY = y;
	}

	/** 画笔移动过程设置 */
	private void touch_move(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(y - mY);
		// 触摸间隔大于阈值才绘制路径
		if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
			// 从x1,y1到x2,y2画一条贝塞尔曲线，更平滑(直接用mPath.lineTo也是可以的)
			mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			mX = x;
			mY = y;
		}
	}

	/** 画图离开画布动作设置 */
	private void touch_up(float x, float y) {

		mPath.lineTo(mX, mY);
		mCanvas.drawPath(mPath, mPaint);
		//将一条完整的路径保存下来(相当于入栈操作)
		savePath.add(dp);
		mPath = null;// 重新置空
		//mPath.reset();
	}
	/** 清空画布 */
	public void clear(){
		mBitmap = Bitmap.createBitmap(ScreenWidth, ScreenHeight,
			    Bitmap.Config.ARGB_8888);
		mCanvas.setBitmap(mBitmap);// 重新设置画布，相当于清空画布
		mCanvas.drawColor(White); // 画布的背景色
		savePath.clear();
		invalidate();// 刷新
	}
	
	/**
	  * 撤销的核心思想就是将画布清空，
	  * 将保存下来的Path路径最后一个移除掉，
	  * 重新将剩余的路径画在画布上面。
	  */
	public void undo() {
	  mBitmap = Bitmap.createBitmap(ScreenWidth, ScreenHeight,
	    Bitmap.Config.ARGB_8888);
	  mCanvas.setBitmap(mBitmap);// 重新设置画布，相当于清空画布
	  mCanvas.drawColor(White); // 画布的背景色
	  // 清空画布，但是如果图片有背景的话，则使用上面的重新初始化的方法，用该方法会将背景清空掉...
	  if (savePath != null && savePath.size() > 0) {
	   // 移除最后一个path,相当于出栈操作
	   savePath.remove(savePath.size() - 1);
	   Iterator<DrawPath> iter = savePath.iterator();
	   while (iter.hasNext()) {
	    DrawPath drawPath = iter.next();
	    mCanvas.drawPath(drawPath.path, drawPath.paint);
	   }
	   invalidate();// 刷新
	   
	  }
	}

	/** 点击底部保存选项后将当前画布保存到SD卡内并录入数据库 */
	private void save() {
		newpaint_title = et_paint_title.getText().toString() + ".jpg";

		ArrayList<HashMap<String, Object>> list = new PaintDao(
				NewPaintActivity.instance).getPaintAllCount();
		HashMap<String, Object> map1 = null;
		boolean flag = false;
		for (int i = 0; i < list.size(); i++) {
			map1 = new HashMap<String, Object>();
			map1 = list.get(i);
			String title = (String) map1.get("title");
			// 如果用户不是新建而是打开某一个文件，保存时文件名与打开的文件名不同
			// 但是与列表中其他文件名相同，则提示不能保存
			if (newpaint_title.equals(title)
					&& !newpaint_title.equals(oldTitle)) {
				flag = true;
				break;
			}
		}
		if (!flag) {
			for (int i = 0; i < list.size(); i++) {
				map1 = new HashMap<String, Object>();
				map1 = list.get(i);
				String title = (String) map1.get("title");
				// 若用户打开了某一个文件更新完没有改原文件名，则删除列表中的源文件
				// 保存新文件
				if (newpaint_title.equals(oldTitle) && title.equals(oldTitle)) {
					new PaintDao(NewPaintActivity.instance).deletePaint(map1);
				}
			}
			saveToSD();
			if(saveSuccess==true){
				saveToDB();
			}
		} else {
			Toast.makeText(NewPaintActivity.instance, "该文件名已存在，请重新输入",
					Toast.LENGTH_SHORT).show();
		}
	}

	/** 点击底部保存选项后将当前画布保存到SD卡内 */
	public void saveToSD() {
		newpaint_title = et_paint_title.getText().toString() + ".jpg";
		if (newpaint_title.equals(".jpg")) {
			newpaint_title = ImageManager.createFileName();
		}
		FileOutputStream fos = null;
		try {
			// 在SD卡中创建MFNote文件夹和image子文件夹
			String SavePath = getSDCardPath() + "/MFNote/image";
			File path = new File(SavePath);
			filepath = SavePath + "/" + newpaint_title;

			File file = new File(filepath);
			if (!path.exists()) {
				path.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
			if (null != fos) {
				mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
			}
		} catch (Exception e) {
//			Toast.makeText(NewPaintActivity.instance, "保存失败",
//					Toast.LENGTH_SHORT).show();
			saveSuccess=false;
			e.printStackTrace();
		} finally{
			try {
				if(fos!=null){
					fos.flush();
					fos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/** 点击保存后将画布信息录入数据库 */
	private void saveToDB() {

		Date date = new Date(System.currentTimeMillis()); // 系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		timeNow = dateFormat.format(date);

		PaintEntity paintEntity = new PaintEntity(newpaint_title, filepath,
				timeNow);
		long state = new PaintDao(NewPaintActivity.instance)
				.insertPaint(paintEntity);
		if (state != -1) {
			Toast.makeText(NewPaintActivity.instance, "保存成功",
					Toast.LENGTH_SHORT).show();
			// 保存完成后跳转到列表界面
			Intent intent = new Intent(NewPaintActivity.instance,
					PaintActivity.class);
			NewPaintActivity.instance.setResult(1);
			NewPaintActivity.instance.startActivity(intent);
			NewPaintActivity.instance.finish();
			NewPaintActivity.instance.overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
		}
	}

	/** 获取SD卡路径 */
	public static String getSDCardPath() {
		String sdcardDir = null;
		boolean sdcardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) { // 判断是否有SD卡
			sdcardDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
		} else {
			Toast.makeText(NewPaintActivity.instance, "没有找到SD卡",
					Toast.LENGTH_SHORT).show();
		}

		return sdcardDir;
	}

	/** 加载涂鸦详情 */
	private void loadPaintDetail() {

		if (!oldTitle.equals("点我开始涂鸦")) {
			int newlength = oldTitle.length() - 4; // 点击后显示的标题长度（去掉.jpg）
			et_paint_title.setText(oldTitle.substring(0, newlength));
			et_paint_title.setSelection(newlength); // 让光标显示在内容后面

			// 获取画布并重绘
			String pathName = getSDCardPath() + "/MFNote/image/" + oldTitle;
			bmpOld = BitmapFactory.decodeFile(pathName);
			mCanvas.drawBitmap(bmpOld, 0, 0, new Paint());
			if (bmpOld != null && !bmpOld.isRecycled()) {
				bmpOld.recycle();
			}
		}

	}

}
